package main

import (
	"fmt"
	"net"
)

const DefaultTcpPort int = 9900

type Listener struct {
	port      int
	dbo       *DBOperation
	manager   *ConnManager
	blacklist *IpBlacklist
}

func Listen(cfg *Config, dbo *DBOperation, connMan *ConnManager) error {
	if cfg.TcpPort == 0 {
		cfg.TcpPort = DefaultTcpPort
	}
	l := NewListener(cfg, dbo, connMan)
	return l.listen()
}

func NewListener(cfg *Config, dbo *DBOperation, connMan *ConnManager) *Listener {
	l := Listener{port: cfg.TcpPort, dbo: dbo, manager: connMan, blacklist: NewIpBlacklist()}
	bl := l.dbo.GetIpBlacklists()
	l.blacklist.Import(bl)
	return &l
}

func (p *Listener) listen() error {
	sPort := fmt.Sprintf(":%d", p.port)
	listener, err := net.Listen("tcp", sPort)

	if err != nil {
		zLog(nil, err.Error())
		return err
	}

	defer func() {
		if err := recover(); err != nil {
			zLog(nil, "监听出现异常：", err)
		}
		listener.Close()
	}()

	zLog(nil, "接收器服务器开始监听TCP端口:", sPort)

	for {
		conn, err := listener.Accept()
		if err != nil {
			zLog(nil, err)
			continue
		}
		go p.handler(conn)
		/*


			if p.blacklist.IsLegal(conn.RemoteAddr().String()) {
				go p.handler(conn)
			} else {
				zLog(&conn, "非法IP地址，禁止连接")
				conn.Close()
			}
		*/
	}
}

func (p *Listener) handler(conn net.Conn) {

	zLog(&conn, "已连接")

	rc := NewReceiverConn(&conn, p.dbo, p.manager, p.blacklist)

	defer func() {
		if err := recover(); err != nil {
			zLog(nil, "连接处理函数出现异常：", err)
		}

		conn.Close()

		p.manager.Delete(rc.terminalId)

		if rc.terminalId != "" {
			p.dbo.SetReceiverStatus(rc.terminalId, ReceiverStatusOffline)
		}
		zLog(&conn, rc.terminalId, "已断开")
	}()

	rc.Do()
}
